import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fsharing/core/models/store_index.dart' as storeIndex;
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/home/store_index_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/store/product_page.dart';
import 'package:fsharing/ui/pages/store/store_page.dart';
import 'package:fsharing/ui/widgets/count_down_badge.dart';
import 'package:provider/provider.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<AppStoreModel, StoreIndexModel>(
      create: (context) => StoreIndexModel(
        Provider.of(context, listen: false),
        Provider.of<AppStoreModel>(context, listen: false).bindingStoreId,
      ),
      update: (context, appStoreModel, model) => model..storeId = appStoreModel.currentStoreId,
      child: Consumer<StoreIndexModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget();
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreIndexModel model = Provider.of(context, listen: false);
    final store = model.storeIndex.store;
    return Scaffold(
      appBar: AppBar(
        leading: Container(
          margin: EdgeInsets.only(left: 12),
          child: CachedNetworkImage(imageUrl: store.logoUrl, width: 60, height: 28),
        ),
        title: _SearchWidget(),
        actions: <Widget>[
          InkWell(
            child: Container(
              margin: EdgeInsets.only(right: 15),
              child: Image.asset('assets/images/home/img_switch.png', width: 42),
            ),
            onTap: () {
              _onSwitchClicked(context);
            },
          ),
        ],
      ),
      body: _BodyWidget(),
    );
  }

  void _onSwitchClicked(BuildContext context) async {
    var storeId = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return _SwitchBottomSheetWidget();
      },
    );
    if (storeId is int) {
      AppStoreModel model = Provider.of(context, listen: false);
      model.currentStoreId = storeId;
    }
  }
}

class _SwitchBottomSheetWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppStoreModel model = Provider.of(context, listen: false);
    final list = model.storeList.entries.toList();
    return ListView.builder(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        var mapEntry = list[index];
        return ListTile(
          title: Text(mapEntry.value),
          onTap: () {
            Navigator.of(context).pop(int.tryParse(mapEntry.key));
          },
        );
      },
      itemCount: list.length,
    );
  }
}

class _SearchWidget extends StatelessWidget {
  const _SearchWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      borderRadius: BorderRadius.circular(14),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/home/img_search.png'),
            fit: BoxFit.fill,
          ),
        ),
        width: 230,
        height: 28,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              '搜索想要的商品',
              style: TextStyle(fontSize: 12),
            ),
            Image.asset('assets/images/home/ic_search.png', width: 12),
          ],
        ),
      ),
      onTap: () => _onSearchClicked(context),
    );
  }

  void _onSearchClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/search');
  }
}

class _BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreIndexModel model = Provider.of(context, listen: false);
    var storeIndex = model.storeIndex;
    return CustomScrollView(
      slivers: <Widget>[
        if (storeIndex.navigator.length > 0)
          SliverToBoxAdapter(
            child: _NavigatorWidget(
              navigator: storeIndex.navigator,
            ),
          ),
        if (storeIndex.bannerList.length > 0)
          SliverToBoxAdapter(
            child: _BannerWidget(
              list: storeIndex.bannerList,
            ),
          ),
        if (storeIndex.newsList.length > 0)
          SliverPadding(
            padding: EdgeInsets.all(8),
            sliver: SliverToBoxAdapter(
              child: _NewsWidget(
                newsList: storeIndex.newsList,
              ),
            ),
          ),
        if (storeIndex.recommendList.length > 0)
          SliverPadding(
            padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
            sliver: SliverToBoxAdapter(
              child: _HotWidget(
                titleImageName: 'assets/images/home/img_recommend_title.png',
                hotList: storeIndex.recommendList,
              ),
            ),
          ),
        if (storeIndex.hotList.length > 0)
          SliverPadding(
            padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
            sliver: SliverToBoxAdapter(
              child: _HotWidget(
                titleImageName: 'assets/images/home/img_hot_title.png',
                hotList: storeIndex.hotList,
              ),
            ),
          ),
        SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 8),
          sliver: SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return _FloorItemWidget(
                  floor: storeIndex.floorList[index],
                );
              },
              childCount: storeIndex.floorList.length,
            ),
          ),
        ),
      ],
    );
  }
}

class _NavigatorWidget extends StatelessWidget {
  final List<storeIndex.Link> navigator;

  _NavigatorWidget({
    Key key,
    @required this.navigator,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 4, right: 4, bottom: 6.5),
      height: 26.5,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return _NavigatorItemWidget(
            link: navigator[index],
          );
        },
        separatorBuilder: (context, index) {
          return VerticalDivider(
            width: 8,
            color: Colors.transparent,
          );
        },
        itemCount: navigator.length,
      ),
    );
  }
}

class _NavigatorItemWidget extends StatelessWidget {
  final storeIndex.Link link;

  _NavigatorItemWidget({
    Key key,
    @required this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white12,
      borderRadius: BorderRadius.circular(10),
      child: InkWell(
        borderRadius: BorderRadius.circular(10),
        child: Container(
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 8),
          height: 10,
          child: Text(
            link.title,
            style: TextStyle(fontSize: 13),
          ),
        ),
        onTap: () {
          _onItemClicked(context);
        },
      ),
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(
      '/store',
      arguments: StorePageArgs(link.storeId, link.storeAreaId),
    );
  }
}

class _BannerWidget extends StatelessWidget {
  final List<storeIndex.Link> list;

  const _BannerWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 375 / 140,
      child: Swiper(
        itemBuilder: (context, index) {
          return CachedNetworkImage(
            imageUrl: list[index].image,
            fit: BoxFit.cover,
          );
        },
        itemCount: list.length,
        autoplay: true,
      ),
    );
  }
}

class _NewsWidget extends StatelessWidget {
  final List<storeIndex.Link> newsList;

  _NewsWidget({
    Key key,
    @required this.newsList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[
        AspectRatio(
          aspectRatio: 375 / 24,
          child: Material(
            color: Colors.white12,
            child: Swiper(
              scrollDirection: Axis.vertical,
              itemBuilder: (context, index) {
                return _NewsItemWidget(
                  link: newsList[index],
                );
              },
              itemCount: newsList.length,
              autoplay: true,
            ),
          ),
        ),
        SizedBox(
          width: 48,
          height: 24,
          child: FlatButton(
            onPressed: () {
              _onNewsMoreClicked(context);
            },
            padding: EdgeInsets.zero,
            child: Text('更多>'),
          ),
        )
      ],
    );
  }

  void _onNewsMoreClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/news');
  }
}

class _NewsItemWidget extends StatelessWidget {
  final storeIndex.Link link;

  const _NewsItemWidget({
    Key key,
    @required this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 12),
              child: Image.asset(
                'assets/images/home/ic_bulletin.png',
                width: 12,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 8, right: 48),
              child: Text(
                link.title,
                style: TextStyle(fontSize: 13),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/news/detail', arguments: link);
  }
}

class _HotWidget extends StatelessWidget {
  final String titleImageName;
  final List<storeIndex.Link> hotList;

  _HotWidget({
    Key key,
    @required this.titleImageName,
    @required this.hotList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 12, bottom: 10),
          child: Image.asset(
            titleImageName, // 'assets/images/home/img_hot_title.png',
            width: 339,
            height: 28,
          ),
        ),
        Theme(
          data: lightTheme(),
          child: Material(
            borderRadius: BorderRadius.circular(4),
            child: GridView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: 1.25,
              ),
              itemBuilder: (context, index) {
                return _HotLinkItemWidget(
                  link: hotList[index],
                );
              },
              itemCount: hotList.length,
            ),
          ),
        )
      ],
    );
  }
}

class _HotLinkItemWidget extends StatelessWidget {
  final storeIndex.Link link;

  _HotLinkItemWidget({
    Key key,
    @required this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      borderRadius: BorderRadius.circular(4),
      child: Stack(
        children: <Widget>[
          Center(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CachedNetworkImage(
                imageUrl: link.image,
                fit: BoxFit.contain,
              ),
            ),
          ),
          CountDownBadge(
            startTime: link.startTime,
            endTime: link.endTime,
            serverTime: link.serverTime,
          ),
        ],
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(
      '/product',
      arguments: ProductPageArgs(link.modelInAreaId, link.storeId),
    );
  }
}

class _FloorItemWidget extends StatelessWidget {
  final storeIndex.Floor floor;

  const _FloorItemWidget({
    Key key,
    @required this.floor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 新列表
    var list = floor.productLinks.toList();
    // 找出BIG_IMAGE
    var link = list.firstWhere(
      (link) => link.displayType == 'BIG_IMAGE',
      orElse: () => null,
    );
    // 移除BIG_IMAGE
    list.removeWhere((link) => link.displayType == 'BIG_IMAGE');
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          margin: EdgeInsets.all(8),
          child: Text(
            floor.title,
            style: TextStyle(fontSize: 21, fontWeight: FontWeight.bold),
          ),
        ),
        if (link != null)
          Container(
            width: double.infinity,
            height: 93,
            margin: EdgeInsets.only(bottom: 8),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: CachedNetworkImage(
                imageUrl: link.image,
                fit: BoxFit.fill,
              ),
            ),
          ),
        GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 8,
            crossAxisSpacing: 8,
            childAspectRatio: 0.8,
          ),
          itemBuilder: (context, index) {
            return _FloorLinkItemWidget(
              link: list[index],
            );
          },
          itemCount: list.length,
        ),
      ],
    );
  }
}

class _FloorLinkItemWidget extends StatelessWidget {
  final storeIndex.Link link;

  _FloorLinkItemWidget({
    Key key,
    this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        borderRadius: BorderRadius.circular(4),
        child: InkWell(
          borderRadius: BorderRadius.circular(4),
          child: Stack(
            children: <Widget>[
              Column(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(4),
                    ),
                    child: CachedNetworkImage(
                      imageUrl: link.image,
                      width: 175.5,
                      height: 175.5,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(4, 4, 4, 0),
                    child: Text(
                      link.title,
                      style: TextStyle(fontSize: 13),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              CountDownBadge(
                startTime: link.startTime,
                endTime: link.endTime,
                serverTime: link.serverTime,
              ),
            ],
          ),
          onTap: () {
            _onItemClicked(context);
          },
        ),
      ),
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(
      '/product',
      arguments: ProductPageArgs(link.modelInAreaId, link.storeId),
    );
  }
}
